package com.bitrate.dagger.mongo.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import com.bitrate.dagger.mongo.convert.DateToLocalDateTimeConvert;
import com.bitrate.dagger.mongo.convert.LocalDateTimeToDateConvert;

import lombok.extern.slf4j.Slf4j;

/**
 * Mongo 构造器
 * 
 * @intro 1.添加了Date LocalDateTime的相互转换,支持JDK1.8+的常用LocalDateTime
 * @intro 2.此处是去除插入数据库的 _class字段
 * @intro 3.修复MongoDb存储时差会8小时
 *
 */
@Slf4j
@Configuration
public class MongoConfiguration {

	@Autowired
	private MongoDatabaseFactory mongoDatabaseFactory;

	@Bean
	public MappingMongoConverter mappingMongoConverter(MongoMappingContext mongoMappingContext) {
		mongoMappingContext.setAutoIndexCreation(true);
		mongoMappingContext.afterPropertiesSet();
		DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
		MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
		converter.setTypeMapper(new DefaultMongoTypeMapper(null));
		List<Object> converters = new ArrayList<>();
		converters.add(new DateToLocalDateTimeConvert());
		converters.add(new LocalDateTimeToDateConvert());
		converter.setCustomConversions(new MongoCustomConversions(converters));
		log.info("------------- x-springboot-starter-mongo Init Success-----------");
		return converter;
	}

	@Bean
	public MongoMappingContext mongoMappingContext() {
		// 必须重新注入
		MongoMappingContext mappingContext = new MongoMappingContext();
		return mappingContext;
	}

}
